package com.hefan.oms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cat.common.meta.ImCustomMsgEnum;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;
import com.google.common.collect.Maps;
import com.hefan.common.exception.DataIllegalException;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.DynamicProperties;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.notify.itf.ImChatroomService;
import com.hefan.notify.itf.ImMsgService;
import com.hefan.oms.bean.ImCustomMsgVo;
import com.hefan.oms.bean.PrivateLetter;
import com.hefan.oms.bean.RebalanceVo;
import com.hefan.oms.bean.RedPacketVo;
import com.hefan.oms.itf.MessageService;
import com.hefan.oms.itf.PrivateLetterService;
import com.hefan.user.bean.ThirdPartyUser;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/28.
 */
@Component("privateMessageService")
public class MessageServiceImpl implements MessageService{

    @Resource
    private PrivateLetterService privateLetterService;
    @Resource
    private WebUserService webUserService;
    @Resource
    private ONSProducer onsProducer;
    @Resource
    private ImMsgService imMsgService;
    @Resource
    private LivingRedisOptService livingRedisOptService;
    @Resource
    ImChatroomService imChatroomService;

    private Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public void reBalanceMessage(RebalanceVo rebalanceVo) {
        try {
            if(rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_MESSAGE){
                WebUser user = webUserService.getWebUserInfoByUserId(rebalanceVo.getToId());
                //饭票兑换盒饭,记录直播收入
                PrivateLetter privateLetter = new PrivateLetter();
                privateLetter.setFromId(rebalanceVo.getFromId());
                privateLetter.setToId(rebalanceVo.getToId());
                privateLetter.setFromNickName(rebalanceVo.getNickName());
                privateLetter.setContent(rebalanceVo.getContent() == null ? "" : rebalanceVo.getContent());
                privateLetter.setAddressNickName(user.getNickName());
                privateLetter.setChatRoomFlag(rebalanceVo.getFromId()+"-"+rebalanceVo.getToId());
                logger.info("私信扣费保存私信内容{}",JSONObject.toJSONString(privateLetter));
                privateLetterService.addNewPrivateLetter(privateLetter);
            }

        }catch (Exception e){
            logger.error("私信扣费异常{}", e);
            throw new RuntimeException("私信扣费异常");
        }


    }

    /**
     * 处理直播间im自定义消息，通过mq异步发送
     *
     * @param rebalanceVo
     * @param type        im 类型
     * @param content     im内容
     * @param webUser     送礼人
     * @param userLevel   用户等级 默认0
     * @return
     * @throws
     * @author wangchao
     * @create 2016/11/2 13:38
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public void dealImMessage(RebalanceVo rebalanceVo, String type, String content, WebUser webUser, int userLevel) {
        ImCustomMsgVo im = new ImCustomMsgVo();
        try {
            //判断当前主播直播间是否可以发送im消息
            if (!isSendIm(type, rebalanceVo)) {
                return;
            }
            //发自定义消息
            im.setType(type);
            im.setContent(StringUtils.isBlank(content) ? "" : content);
            im.setGiftId(String.valueOf(rebalanceVo.getPresentId()));
            im.setGiftName(String.valueOf(rebalanceVo.getPresentName()));
            im.setGiftType(String.valueOf(rebalanceVo.getPresentType()));
            im.setGiftUrl(rebalanceVo.getPresentUrl());
            im.setLevel(String.valueOf(userLevel));
            //查询是否被禁言
//            /*boolean isMute = roomShutupService
//                .findIsShutupForAnchorByUserId(rebalanceVo.getFromId(), rebalanceVo.getLiveUuid(), Integer.parseInt(StringUtils.isBlank(rebalanceVo.getRoomId()) ? "0" : rebalanceVo.getRoomId()));*/
            boolean isMute=livingRedisOptService.isShutUpUser(rebalanceVo.getLiveUuid(),rebalanceVo.getFromId());
            logger.info("送礼人{}是否被禁言:{}",rebalanceVo.getFromId(), isMute);

            im.setIsMute(isMute ? 1 : 0);
            im.setGcount(String.valueOf(rebalanceVo.getPresentNum()));
            //返回主播的所有盒饭数,如果世界礼物不显示主播盒饭数
            //            if (!rebalanceVo.getToId().equals(GlobalConstants.HEFAN_OFFICIAL_ID)) {
            WebUser toUser = webUserService.getWebUserInfoByUserId(rebalanceVo.getToId());
            im.setHeFanNum(String.valueOf(toUser.getHefanTotal()));
            //            }
            //重新封装user对象，避免用户敏感信息泄露
            ThirdPartyUser user = new ThirdPartyUser();
            user.setHeadImg(webUser.getHeadImg());
            user.setUserLevel(userLevel == 0 ? webUser.getUserLevel() : userLevel);
            user.setNickName(webUser.getNickName());
            user.setUserId(webUser.getUserId());
            user.setUserType(webUser.getUserType());
            user.setLiveUuid(rebalanceVo.getLiveUuid().equals("club") ? "" : rebalanceVo.getLiveUuid());
            // 给队列发消息，完成后续工作
            String onsEnv = DynamicProperties.getString("ons.env");
            com.hefan.common.ons.bean.Message message = new com.hefan.common.ons.bean.Message();

            message.setTag(onsEnv);
            message.put("roomId", rebalanceVo.getRoomId());
            /*message.put("imMessage", URLEncoder.encode(JSON.toJSONString(im),"UTF-8"));*/
            message.put("imMessage", JSON.toJSONString(im));
            message.put("toUserId", rebalanceVo.getToId());
            //弹幕 发送im主体为扣费用户，其他均为主播id
            if (rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_BARRAGE) {
                message.put("toUserId", rebalanceVo.getFromId());
            }
            message.put("fromUser", JSON.toJSONString(user));
            message.setTopic(TopicRegistry.HEFANTV_OMS_IM);
            logger.info("MessageService扣费IM通知前端内容{}", JSONObject.toJSONString(message));
            onsProducer.sendMsg(message);

        } catch (Exception e) {
            logger.error("IM{},通知异常{}", JSONObject.toJSONString(im), e);
        }
    }

    private boolean isSendIm(String type,RebalanceVo rebalanceVo){
        int iMType = -1;
        String msgType = "小礼物";
        if (type.equals(ImCustomMsgEnum.BarrageMsg.getType())) {
            //如果弹幕
            iMType = 4;
            msgType = ImCustomMsgEnum.BarrageMsg.getMsg();
        } else if (type.equals(ImCustomMsgEnum.PresentChange.getType())) {
            //盒饭数变化
            iMType = 1;
            msgType = ImCustomMsgEnum.PresentChange.getMsg();
        } else if (rebalanceVo.getHoutaiPresentType() == GlobalConstants.PRESENT_TYPE_SMALL) {
            //小礼物
            iMType = 0;
        }
        if (iMType > -1) {
            boolean flag = livingRedisOptService.IMSendCheck(rebalanceVo.getToId(), iMType);
            if (!flag) {
                logger.error("主播{}，直播间id{}允许发送的{}IM已达上限", rebalanceVo.getToId(), rebalanceVo.getLiveUuid(), msgType);
                return false;
            }
        }
        return true;
    }

    @Override
    public void dealRedPacketImMessage(RedPacketVo redPacketVo, String type,String content, WebUser webUser,List<Map<String,String>> plist,long orderId) {
        ImCustomMsgVo im = new ImCustomMsgVo();
        //发自定义消息
        im.setType(type);
        im.setContent(content);
        im.setGiftId(String.valueOf(redPacketVo.getPresentId()));
        im.setGiftName(redPacketVo.getPresentName());
        im.setGiftUrl(redPacketVo.getPresentUrl());
        im.setGiftType("0");
        im.setLevel(String.valueOf(webUser.getUserLevel()));
        im.setIsMute(0);
        if (!CollectionUtils.isEmpty(plist)) {
            im.setRedList(plist);
            im.setRedId(String.valueOf(orderId));
        }
        im.setGcount("1");
        WebUser toUser = webUserService.getWebUserInfoByUserId(redPacketVo.getZhuboId());
        im.setHeFanNum(String.valueOf(toUser.getHefanTotal()));
        //重新封装user对象，避免用户敏感信息泄露
        ThirdPartyUser user = new ThirdPartyUser();
        user.setHeadImg(webUser.getHeadImg());
        user.setUserLevel(webUser.getUserLevel());
        user.setNickName(webUser.getNickName());
        user.setUserId(webUser.getUserId());
        user.setUserType(webUser.getUserType());
        user.setLiveUuid(redPacketVo.getLiveUuid());
        imChatroomService.chatroomSendMsg(Long.valueOf(redPacketVo.getRoomId()), redPacketVo.getZhuboId(), 100, 0, JSON.toJSON(im).toString(), JSONObject.toJSONString(user));
    }

    /**
     * 私信IM通讯
     *
     * @param rebalanceVo
     */
    @Override
    public void dealPrivateMessage(RebalanceVo rebalanceVo,WebUser webUser) {

        try {
            //消息类型5文本6表情，文本普通消息，表情自定义消息
            int presentType=rebalanceVo.getPresentType();
            Map<String,String> map= Maps.newHashMap();
            //map.put("type",ImCustomMsgEnum.MESSAGE.getType());
            map.put("msg",rebalanceVo.getContent());
            map.put("content",rebalanceVo.getContent());
            logger.info("用户{}发送私信内容{}",JSONObject.toJSONString(rebalanceVo),JSONObject.toJSONString(map));
            imMsgService.msgsendMsg(rebalanceVo.getFromId(), "0", rebalanceVo.getToId(), presentType == 5 ? "0" : "100", JSONObject.toJSONString(map), "", "", "", "", "", "", "");
        } catch (Exception e) {
            logger.error("IM私信通知异常{}", e);
            throw new DataIllegalException("IM私信通知异常{}"+e);
        }
    }

}
